/*
 * @Author: wuqingchun
 * @Date: 2024-09-24 08:51:42
 * @Description: 
 * @LastEditors: wuqingchun
 * @LastEditTime: 2024-10-01 16:33:57
 */
#include <stdio.h>

#include "../chat_errno.h"
#include "../chat_config.h"
#include "chat_db_mysql.h"


CChatDBMysql& CChatDBMysql::GetInstance()
{
    static CChatDBMysql objMysql;

    return objMysql;
}

CChatDBMysql::CChatDBMysql()
{

}

CChatDBMysql::~CChatDBMysql()
{
    if (m_pstMysqlConn != nullptr)
    {
        mysql_close(m_pstMysqlConn);
        m_pstMysqlConn = nullptr;
    }
}

int32_t CChatDBMysql::Init()
{
    m_pstMysqlConn = mysql_init(nullptr);
    if (m_pstMysqlConn == nullptr)
    {
        printf("Failed to init mysql\n");
        return CHAT_ERR_MYSQL_INIT;
    }

    const CHAT_MYSQL_CONFIG_S& refConfig = CChatConfig::GetInstance().GetMysqlConfig();
    
    if (mysql_real_connect(m_pstMysqlConn, 
                           refConfig.strHost.c_str(), 
                           refConfig.strUser.c_str(), 
                           refConfig.strPassword.c_str(), 
                           refConfig.strDBName.c_str(), 
                           refConfig.usPort, nullptr, 0) == nullptr)
    {
        m_pstMysqlConn = nullptr;
        printf("Failed to connect mysql server[%s:%hu], database=%s\n", refConfig.strHost.c_str(), 
               refConfig.usPort, refConfig.strDBName.c_str());

        return CHAT_ERR_MYSQL_INIT;
    }

    // 设置字符集，与mysql服务器保持一致
    int iErr = mysql_set_character_set(m_pstMysqlConn, refConfig.strCharset.c_str());
    if (iErr != 0)
    {
        return CHAT_ERR_MYSQL_INIT;
    }

    printf("Succeed to connect mysql server[%s:%hu], database=%s\n", refConfig.strHost.c_str(), 
           refConfig.usPort, refConfig.strDBName.c_str());
    return CHAT_ERR_OK;
}

int32_t CChatDBMysql::ExecuteSQL(const char* pcSQL, MYSQL_RES** ppstResult)
{
    if (pcSQL == nullptr)
    {
        return CHAT_ERR_INVALID_PARAMETER;
    }

    if (m_pstMysqlConn == nullptr)
    {
        printf("Not connected with mysql server\n");
        return CHAT_ERR_MYSQL_INIT;
    }

    printf("SQL: %s\n", pcSQL);

    int32_t iErr = mysql_query(m_pstMysqlConn, pcSQL);
    if (iErr != 0)
    {
        printf("Failed to execute SQL, %s\n", pcSQL);
        return CHAT_ERR_MYSQL_EXEC;
    }

    if (ppstResult != nullptr)
    {
        *ppstResult = mysql_store_result(m_pstMysqlConn);
        if (*ppstResult == nullptr)
        {
            return CHAT_ERR_MYSQL_RESULT;
        }
    }

    return CHAT_ERR_OK;
}